﻿using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Infrastructure;
using Xoohoo.Models.ViewModels;

namespace Xoohoo.ActionFilters.Action
{
    public class UserActionFilter : IActionFilter
    {
        private readonly IModuleRegistry _modules;

        public UserActionFilter(IModuleRegistry modules)
        {
            this._modules = modules;
        }

        #region IActionFilter Members

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            XoohooViewModel model = filterContext.Controller.ViewData.Model as XoohooViewModel;

            if (model != null)
            {
                IUser user = null;

                if (filterContext.HttpContext.Items.Contains(typeof(IUser).FullName))
                {
                    user = filterContext.HttpContext.Items[typeof(IUser).FullName] as IUser;
                }

                if (user != null && user.IsAuthenticated)
                {
                    model.User = new UserViewModel(user);
                }
                else
                {
                    model.User = new UserViewModel(filterContext.HttpContext.Request.Cookies.GetAnonymousUser());
                }
            }
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
        }

        #endregion
    }
}
